import 'dart:convert';
import 'dart:io';

import 'package:HAHA/utils/shared_preferences_util.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

import '../components/custom_toast.dart';
import '../config/nav_key.dart';
import '../models/base_model.dart';
import '../pages/login/login_page.dart';

class HttpUtil {
  static Dio? _dio;
  final Logger logger = Logger();

  static Dio get dio {
    if (_dio == null) {
      // 配置Dio实例
      BaseOptions options = BaseOptions(
        baseUrl: "http://192.168.2.14:8888/user", // 你的API地址
        connectTimeout: const Duration(milliseconds: 10000), // 设置连接超时时间为10秒
        receiveTimeout: const Duration(milliseconds: 10000), // 设置接收数据超时时间为10秒
      );

      _dio = Dio(options);

      // 可以添加拦截器、日志等其他配置

      // 添加请求拦截器
      _dio!.interceptors.add(InterceptorsWrapper(
        onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
          if (kDebugMode) {
            print("\n");
            print("\n");
            print("========================请求数据===================");
            print("url=${options.uri.toString()}");
            print("params=${options.data}");
            print("headers=${options.headers}");
          }

          // 在请求之前做一些操作，比如添加token等
          return handler.next(options);
        },
        onResponse: (Response response, ResponseInterceptorHandler handler) {
          if (kDebugMode) {
            print("\n");
            print("\n");
            print("========================响应数据===================");
            print("code=${response.statusCode}");
            print("response=${response.data}");
            print("==================================================");
            print("\n");
            print("\n");
            print("\n");
          }

          // 在响应之前做一些操作
          return handler.next(response);
        },
        onError: (DioException e, ErrorInterceptorHandler handler) {
          // 在错误之前做一些操作
          if (e.response?.statusCode == 401) {
            CustomToast.showErrorToast("您的登录状态已经过期了哦~");
            // 清除token信息
            SharedPreferencesUtil.remove("token");
            Navigator.of(NavKey.navKey.currentState!.context).push(
              MaterialPageRoute(
                builder: (context) => const LoginPage(),
              ),
            );
            return;
          }
          return handler.next(e);
        },
      ));
    }

    return _dio!;
  }

  // 封装GET请求
  static Future<dynamic> get(String path,
      {Map<String, dynamic>? queryParameters}) async {
    try {
      Map<String, dynamic> header = <String, dynamic>{};
      header["Authorization"] = await SharedPreferencesUtil.getString("token");

      Response response = await dio.get(
        path,
        queryParameters: queryParameters,
        options: Options(headers: header),
      );

      BaseModel baseModel = BaseModel.fromJson(response.data);
      if (baseModel.code == 1) {
        return baseModel.data; // 返回成功的数据
      } else {
        // 打印错误信息
        print('错误代码: ${baseModel.code}, 错误信息: ${baseModel.msg}');
        return null; // 或者返回其他适当的值
      }
    } catch (e) {
      print('请求失败: $e'); // 打印请求错误信息
      rethrow; // 重新抛出异常
    }
  }

  // 封装POST请求，数据以JSON格式发送
  static Future<Response> post(String path,
      {Map<String, dynamic>? data,
      Map<String, dynamic>? queryParameters}) async {
    try {
      Map<String, dynamic> header = <String, dynamic>{};
      header["Authorization"] = await SharedPreferencesUtil.getString("token");

      Response response = await dio.post(
        path,
        data: jsonEncode(data),
        queryParameters: queryParameters,
        options: Options(contentType: 'application/json', headers: header),
      );
      return response;
    } catch (e) {
      rethrow;
    }
  }

  // 封装POST请求，数据以form表单格式发送
  static Future<Response> postForm(String path,
      {Map<String, dynamic>? data}) async {
    try {
      Response response = await dio.post(
        path,
        queryParameters: data,
      );
      return response;
    } catch (e) {
      rethrow;
    }
  }

  static Future<Response> uploadImage(String path, File image) async {
    try {
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(image.path),
      });

      Map<String, dynamic> header = <String, dynamic>{};
      header["Authorization"] = await SharedPreferencesUtil.getString("token");
      header["Content-Type"] = "multipart/form-data";

      Response response = await dio.post(
        path,
        data: formData,
        options: Options(headers: header),
        onSendProgress: (int sent, int total) {
          if (kDebugMode) {
            print('上传进度: ${(sent / total * 100).toStringAsFixed(2)}%');
          }
        },
      );

      return response;
    } catch (e) {
      rethrow;
    }
  }
}
